package com.xia.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.xia.util.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.nio.ch.FileKey;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${online.leading-end-agreement}")
    private String leadingEndAgreement;

    @Value("${online.img-location}")
    private String imgLocation;

    @PostMapping("/upload")
    public Result articleContentImage(MultipartFile file) throws IOException {
        String originalFilename=file.getOriginalFilename();
        String flag= IdUtil.fastSimpleUUID();
        String rootFilePath=imgLocation+flag+"_"+originalFilename;
        FileUtil.writeBytes(file.getBytes(),rootFilePath);
        return Result.success(leadingEndAgreement + "/static/img/"+flag+"_"+originalFilename);
    }

    @DeleteMapping("/delete")
    public void articleDeleteImage(String[] allImage){
        for (String fileName : allImage) {
            String imageName = imgLocation + fileName;
            System.out.println(imageName);
            File file=new File(imageName);
            System.out.println(file.delete());
        }
    }

    @GetMapping("/download/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        List<String> fileNames = FileUtil.listFileNames(imgLocation);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name ->name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(imgLocation + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }
}
